# -*- coding: utf-8 -*-
# @Time    : 3/16/2019 23:28
# @Author  : MARX·CBR
# @File    : 解压zip文件.py
import zipfile
import sys
import lxml
from bs4 import BeautifulSoup
import os
import shutil

import gc

gc.set_threshold(256, 8, 8)


class MarxTool:
    def __init__(self, src, des):
        self.marx = 0
        self.path = src
        self.extract_information = des + "/"
        self.extract_path = des + '/unzip_folder/'
        self.extract_images = des + '/extract_images/'
        self.fullPath = []
        self.number = 0

    def logging_to_file(self, file_name, content):

        template = '''
        \n
        ///////////////////////////////
        //  以下内容来自：{}  //
        ///////////////////////////////
        \n{}
        '''.format("extract_{}/".format(self.number) + file_name, content)

        with open("./Files_information.txt", 'a+', encoding='utf-8') as f:
            f.write(template)

    def unzip(self, file):
        # print(zipfile.is_zipfile(file))
        try:
            f = zipfile.ZipFile(file, 'r')
            for files in f.namelist():
                path = self.extract_path + "extract_{}/".format(self.number)
                f.extract(files, path=path)
                try:
                    self.match_time(path=path)
                except:
                    print("match time fail")

                try:
                    self.match_document(path=path)
                except:
                    print("match_document fail")

                try:
                    self.match_ppt_content(path=path)
                except:
                    print("match_ppt_content fail")

                try:
                    self.match_xlsx_content(path=path)
                except:
                    print("match_xlsx_content fail")

                try:
                    src = path + files
                    aim = self.extract_images

                    if "png" in files:
                        shutil.move(src, aim)
                    elif "jpg" in files:
                        shutil.move(src, aim)
                    elif "jpeg" in files:
                        shutil.move(src, aim)
                    elif "gif" in files:
                        shutil.move(src, aim)
                    elif "bmp" in files:
                        shutil.move(src, aim)
                except:
                    print("move image fail")

            self.number += 1
        except:
            print("fail to extract")

    def find_all_zip(self):
        for dirpath, dirnames, filenames in os.walk(self.path):
            for file in filenames:
                if str(file)[-3::] == 'zip':
                    fullpath = os.path.join(dirpath, file)
                    self.fullPath.append(fullpath)
        print(self.fullPath)

    def unzip_all_file_to_temp(self):
        for file in self.fullPath:
            self.unzip(file)
        try:
            with open("flag", 'w') as f:
                f.write("1")
        except:
            print("完成标志修改错误")
        shutil.copy("./Files_information.txt", self.extract_information)
        print('解压完成')

    def match_time(self, path):
        with open('{}/docProps/core.xml'.format(path), 'r', encoding='utf-8') as f:
            con = f.read()
        soup = BeautifulSoup(con, 'lxml')
        print(soup)

        content = "最后修改者：{}\n文件创建者：{}\n文件创建时间：{}\n文件修改时间：{}\n".format(soup.find('cp:lastmodifiedby').get_text(),
                                                                      soup.find('dc:creator').get_text(),
                                                                      soup.find('dcterms:created').get_text(),
                                                                      soup.find('dcterms:modified').get_text())

        self.logging_to_file("/docProps/core.xml", content=content)

    def match_document(self, path):
        with open('{}/word/document.xml'.format(path), 'r', encoding='utf-8') as f:
            con = f.read()
        soup = BeautifulSoup(con, 'lxml')
        print(soup)
        content = ""
        for gg in soup.findAll('w:t'):
            content += gg.get_text() + "\t"

        self.logging_to_file("/word/document.xml", content=content)

    def match_ppt_content(self, path):
        files = os.listdir('{}/ppt/slides/'.format(path))
        for slide in files:
            with open('{}/ppt/slides/{}'.format(path, slide), 'r', encoding='utf-8') as f:
                con = f.read()
            soup = BeautifulSoup(con, 'lxml')
            print(soup)
            # print(soup.findAll('a:t'))
            content = ""
            for gg in soup.findAll('a:t'):
                content += gg.get_text() + "\t"

            self.logging_to_file("/ppt/slides/{}".format(slide), content=content)

    def match_xlsx_content(self, path):

        files = os.listdir('{}/xl/worksheets/'.format(path))
        for sheet in files:
            with open('{}/xl/worksheets/{}'.format(path, sheet), 'r', encoding='utf-8') as f:
                con = f.read()
            soup = BeautifulSoup(con, 'lxml')
            # print(soup)
            # print(soup.findAll('v'))
            content = ""
            for gg in soup.findAll('v'):
                content += gg.get_text() + "\t"

            self.logging_to_file('/xl/worksheets/{}'.format(sheet), content=content)

        with open('{}/xl/sharedStrings.xml'.format(path), 'r', encoding='utf-8') as f:
            con = f.read()
        soup = BeautifulSoup(con, 'lxml')
        # print(soup)
        # print(soup.findAll('t'))
        content = ""
        for gg in soup.findAll('t'):
            content += gg.get_text() + "\t"

        self.logging_to_file('/xl/sharedStrings.xml', content=content)


# MarxTool.fixBadZipfile(r'W:\Python_Year4\temp\test\catalog_9\themeMan.zip')
# MarxTool.unzip(r'D:\test\office_source\catalog_0\[Content_Types].xml.zip')


# MarxTool.match_time()
# MarxTool.match_xlsx_content()
if __name__ == '__main__':
    print('提取压缩包内容 并解析\n Input:')
    if len(sys.argv) == 1:
        print('Please input parameter')
        sys.exit()
    elif len(sys.argv) == 2:
        print('Please input parameter')
        sys.exit()
    elif len(sys.argv) == 3:
        src = sys.argv[1]
        des = sys.argv[2]
        MarxTool = MarxTool(src=src, des=des)
        if os.path.exists(MarxTool.extract_images):
            print("ok")
        else:
            os.mkdir(MarxTool.extract_images)
        with open("./Files_information.txt", 'w', encoding='utf-8') as f:
            f.write(" WelcomeToTheSystem ")

        MarxTool.find_all_zip()
        MarxTool.unzip_all_file_to_temp()
    else:
        print("Cannot run this parameter")
